package com.haixiaoke.saas.common.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.haixiaoke.saas.common.core.redis.RedisCache;
import com.haixiaoke.saas.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 设备管理平台配置
 *
 * @author qixi
 * @date 2024/7/25
 */
@Component
@Slf4j
public class DevicesConfig {


    final String key = "DevicesConfig_token";

    @Autowired
    private RedisCache redisCache;

    /**
     * username
     */
    @Value("${devices.username}")
    private String username;

    /**
     * password
     */
    @Value("${devices.password}")
    private String password;


    @Value("${devices.url}")
    private String url;


    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }


    public String getToken() {
        Object cacheObject = redisCache.getCacheObject(key);
        if (cacheObject != null) {
            return ObjectUtil.toString(cacheObject);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        String result = HttpRequest.post(url + "/third-party/login")
                .body(JSONObject.toJSONString(map))
                .header("Content-Type", "application/json;charset=UTF-8")
                .execute()
                .body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getObject("code", Integer.class);
        if (code == 200) {
            String token = jsonObject.getString("token");
            redisCache.setCacheObject(key, token, 25, TimeUnit.MINUTES);
            return "Bearer " + token;
        } else {
            log.error("获取设备平台token失败：" + result);
            return null;
        }
    }

    public JSONObject sendRequest(RequestMethod method, Object data, String requestUrl) {
        String token = this.getToken();
        String result = "";
        if (method == RequestMethod.GET) {
            result = HttpRequest.get(url + requestUrl)
                    .header("Authorization", token)
                    .execute()
                    .body();

        } else if (method == RequestMethod.POST) {
            result = HttpRequest.post(url + requestUrl)
                    .body(JSONObject.toJSONString(data))
                    .header("Content-Type", "application/json")
                    .header("Authorization", token)
                    .execute()
                    .body();
        } else if (method == RequestMethod.DELETE) {
            result = HttpRequest.delete(url + requestUrl)
                    .header("Authorization", token)
                    .execute()
                    .body();
        } else if (method == RequestMethod.PUT) {
            result = HttpRequest.put(url + requestUrl)
                    .body(JSONObject.toJSONString(data))
                    .header("Content-Type", "application/json")
                    .header("Authorization", token)
                    .execute()
                    .body();
        }

        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getObject("code", Integer.class);
        if (code == 200) {
            log.info("请求设备平台成功：" + result);
            return jsonObject;
        } else {
            log.error("请求设备平台失败：" + result);
            throw new ServiceException("请求设备平台失败：" + jsonObject.getString("msg"));
        }
    }
}
